package solutions;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-02-06
 * Time: 16:37
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

//https://leetcode.cn/problems/remove-nth-node-from-end-of-list/submissions/399893793/?envType=study-plan&id=suan-fa-ru-men&plan=algorithms&plan_progress=bmyvagt
class Solution5 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(0, head);
        ListNode slow = dummyHead;
        ListNode fast = head;
        while (n-- > 0) {
            fast = fast.next;
        }
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummyHead.next;
    }
}
